﻿using ServiceCore.DbContext;
using ServiceCore.Entity.Arg;
using ServiceCore.Entity.Const.Record;
using ServiceCore.Entity.Model;
using ServiceCore.Utility.Extension;

namespace ServiceCore.Service
{
    /// <summary>
    /// 标签
    /// </summary>
    public partial class TextParseService : SqlsugarServices<RecordInfo>
    {
        #region 标签解析-各
        public void Text_Parse_Tag_Each_Verify(ArgTextParse arg)
        {
            arg.lstParse = new List<TextParseDto>();
            if (string.IsNullOrEmpty(arg.ErrorMsg) == false)
                return;
            arg.lstParse = arg.Datas.Where(x => x.ParsemChildMode == ParsemChildMode.ParsemChildMode_Tag_Each && x.IsParseSuccess == false).ToList();
            if (arg.lstParse.Any() == false)
                return;

            decimal? value = 0;
            string tagStr = string.Empty;
            string gongStr = string.Empty;
            foreach (var item in arg.lstParse)
            {
                value = NumberExtractor.ExtractDecimalAfterGong(item.SourceProcess, '各');
                if (value.HasValue == false)
                {
                    item.Result = ParsemResult.ParsemResult_Fail;
                    item.ResultTip = "获取金额失败";
                    continue;
                }
                tagStr = item.SourceProcess.Split('各')[0];
                if (string.IsNullOrWhiteSpace(tagStr))
                {
                    item.Result = ParsemResult.ParsemResult_Fail;
                    item.ResultTip = "获取标签失败";
                    continue;
                }
                gongStr = string.Empty;
                if (item.SourceProcess.Contains("共"))
                {
                    gongStr = item.SourceProcess.Split('共')[1];
                }

                tagStr = tagStr.GetTxtReplaceNumeric();
                item.SourceProcess = tagStr + "各" + value;
                if (string.IsNullOrEmpty(gongStr) == false)
                    item.SourceProcess += "共" + gongStr;
            }
        }

        /// <summary>
        /// 标签解析-包含各
        /// </summary>
        /// <param name="arg"></param>
        public void Text_Parse_Tag_Each(ArgTextParse arg)
        {
            Text_Parse_Tag_Each_Verify(arg);
            if (arg.lstParse.Any() == false)
                return;

            decimal? value = 0;
            string tagStr = "";
            var tagNames = new List<string>();
            var tag = new TagInfo();
            foreach (var item in arg.lstParse)
            {
                value = NumberExtractor.ExtractNumberAfterGong(item.SourceProcess, '各');
                if (value.HasValue == false)
                {
                    item.Result = ParsemResult.ParsemResult_Fail;
                    item.ResultTip = "获取金额失败";
                    continue;
                }
                tagStr = item.SourceProcess.Split('各')[0];
                if (string.IsNullOrWhiteSpace(tagStr))
                {
                    item.Result = ParsemResult.ParsemResult_Fail;
                    item.ResultTip = "获取标签失败";
                    continue;
                }

                tagNames = new List<string>();
                if (tagStr.Contains(","))
                    tagNames = tagStr.Split(",").ToList();
                else
                    tagNames.Add(tagStr);
                if (tagNames.Any())
                {
                    tagNames.ForEach(x => x = x.TrimStart().TrimEnd());
                    tagNames = tagNames.Where(x => string.IsNullOrWhiteSpace(x) == false).ToList();
                }
                if (tagNames.Any() == false)
                {
                    item.Result = ParsemResult.ParsemResult_Fail;
                    item.ResultTip = "无对应标签";
                    continue;
                }

                //设置值
                foreach (var tagName in tagNames)
                {
                    tag = arg.lstTag.Where(x => x.Name.ToLong() == tagName.ToLong()).FirstOrDefault();
                    if (tag == null)
                        continue;

                    tag.DataValue = value.Value;
                    item.lstTag.Add(new TagInfo() { Id = tag.Id, TagTypeId = tag.TagTypeId, TagTypeName = tag.TagTypeName, Name = tag.Name, DataValue = value.Value, CreateTime = arg.CurTime });
                }

                //结果校验
                if (item.lstTag.Any())
                {
                    if (item.Total.HasValue && item.lstTag.Sum(x => x.DataValue) != item.Total)
                    {
                        item.Result = ParsemResult.ParsemResult_Warn;
                        item.ResultTip = "不等于合计";
                        continue;
                    }
                    item.Result = ParsemResult.ParsemResult_Success;
                    item.IsParseSuccess = true;
                }
            }
        }
        #endregion

        #region 标签解析-通用
        /// <summary>
        /// 标签解析-通用
        /// </summary>
        /// <param name="arg"></param>
        public void Text_Parse_Tag_General_Verify(ArgTextParse arg)
        {
            arg.lstParse = new List<TextParseDto>();
            if (string.IsNullOrEmpty(arg.ErrorMsg) == false)
                return;
            arg.lstParse = arg.Datas.Where(x => x.ParsemChildMode == ParsemChildMode.ParsemChildMode_Tag_General && x.IsParseSuccess == false).ToList();
            if (arg.lstParse.Any() == false)
                return;

            var commaCnt = 0;
            List<string>? nums;
            foreach (var item in arg.lstParse)
            {
                item.SourceProcess = item.SourceProcess.Replace("  ", " ");
                item.SourceProcess = item.SourceProcess.Replace(" ", ",");
                item.SourceProcess = item.SourceProcess.Replace(" ", ",");
                item.SourceProcess = item.SourceProcess.Replace(".", ",");
                item.SourceProcess = item.SourceProcess.Replace("。", ",");
                item.SourceProcess = item.SourceProcess.Replace("/", ",");
                item.SourceProcess = item.SourceProcess.Replace("-", ",");
                item.SourceProcess = item.SourceProcess.Replace("+", ",");
                item.SourceProcess = item.SourceProcess.Replace("打,", "打");

                if (item.SourceProcess.Contains("号"))
                {
                    item.SourceProcess = item.SourceProcess.Replace("号", "打"); //24号5【失败原因：获取金额失败】
                    item.SourceProcess = item.SourceProcess.Replace("打,", "打"); 
                    continue;
                }
                else if (item.SourceProcess.IsAllNumeric() && item.SourceProcess.Contains(" "))
                {
                    nums = item.SourceProcess.Split(' ').ToList();
                    nums = nums.Where(x => string.IsNullOrWhiteSpace(x) == false).ToList();
                    if (nums.Count % 2 == 0)
                    {
                        //33   25    36  32    30   40
                        item.SourceProcess = string.Empty;
                        for (int i = 0; i < nums.Count; i++)
                        {
                            if (i % 2 == 0)
                                item.SourceProcess += nums[i] + "打";
                            else
                                item.SourceProcess += nums[i] + ";";
                        }
                    }
                    continue;
                }

                commaCnt = item.SourceProcess.GetCharCount(',');
                if (commaCnt == 1)
                {
                    item.SourceProcess = item.SourceProcess.ReplaceLastComma("打"); //10,300元【失败原因：获取金额失败】
                    continue;
                }
                else if (commaCnt > 1)
                {
                    nums = item.SourceProcess.Split(',').ToList();
                    nums = nums.Where(x => string.IsNullOrWhiteSpace(x) == false && x.Contains("共") == false && x.IsHaveNumeric()).ToList();
                    if (nums.Count % 2 == 0)
                    {
                        //33,25, 36,32, 30,40
                        item.SourceProcess = string.Empty;
                        for (int i = 0; i < nums.Count; i++)
                        {
                            if (i % 2 == 0)
                                item.SourceProcess += nums[i] + "打";
                            else
                                item.SourceProcess += nums[i] + ";";
                        }
                    }
                    continue;
                }
            }
        }

        /// <summary>
        /// 标签解析-通用
        /// </summary>
        /// <param name="arg"></param>
        public void Text_Parse_Tag_General(ArgTextParse arg)
        {
            Text_Parse_Tag_General_Verify(arg);
            if (arg.lstParse.Any() == false)
                return;
           
            arg.lstParse.ForEach(x =>
            {
                if (x.SourceProcess.GetCharCount('打') == 1)
                {
                    x = Text_Parse_Tag_General_Single(x, arg.lstTag);
                }
                else
                {
                    x = Text_Parse_Tag_General_Multiple(x, arg.lstTag);
                }

                x.lstTag.ForEach(x => x.CreateTime = arg.CurTime);
            });
        }
        #endregion

        /// <summary>
        /// 标签解析-通用-单个
        /// </summary>
        /// <param name="arg"></param>
        public TextParseDto Text_Parse_Tag_General_Single(TextParseDto item, List<TagInfo> lstTag)
        {
            var value = NumberExtractor.ExtractNumberAfterGong(item.SourceProcess, '打');
            if (value.HasValue == false)
            {
                item.Result = ParsemResult.ParsemResult_Fail;
                item.ResultTip = "获取金额失败";
                return item;
            }

            var tagStr = item.SourceProcess.Split('打')[0];
            if (string.IsNullOrWhiteSpace(tagStr))
            {
                item.Result = ParsemResult.ParsemResult_Fail;
                item.ResultTip = "获取标签内容失败";
                return item;
            }
            tagStr = tagStr.TrimStart().TrimEnd();

            var tags = new List<TagInfo>();
            var tag = new TagInfo();
            if (tagStr.Contains(',') == false)
            {
                //单个
                tag = lstTag.Where(x => x.Name.ToLong() == tagStr.ToLong()).FirstOrDefault();
                if (tag != null)
                    tags.Add(new TagInfo() { Id = tag.Id, TagTypeId = tag.TagTypeId, TagTypeName = tag.TagTypeName, Name = tag.Name, DataValue = value.Value });
            }
            else
            {
                //多个
                var lstTagName = tagStr.Split(",").ToList();
                lstTagName = lstTagName.Where(x => string.IsNullOrWhiteSpace(x) == false).ToList();
                foreach (var _tagName in lstTagName)
                {
                    tag = lstTag.Where(x => x.Name.ToLong() == _tagName.ToLong()).FirstOrDefault();
                    if (tag == null)
                        continue;

                    tags.Add(new TagInfo() { Id = tag.Id, TagTypeId = tag.TagTypeId, TagTypeName = tag.TagTypeName, Name = tag.Name, DataValue = value.Value });
                }
            }

            if (tags.Any() == false)
            {
                item.Result = ParsemResult.ParsemResult_Fail;
                item.ResultTip = "无对应标签";
                return item;
            }
            if (item.Total.HasValue && item.lstTag.Sum(x => x.DataValue) != item.Total)
            {
                item.Result = ParsemResult.ParsemResult_Warn;
                item.ResultTip = "不等于合计";
            }
            else
                item.Result = ParsemResult.ParsemResult_Success;

            item.lstTag.AddRange(tags);
            item.IsParseSuccess = true;
            return item;
        }

        /// <summary>
        /// 标签解析-通用
        /// </summary>
        /// <param name="arg"></param>
        public TextParseDto Text_Parse_Tag_General_Multiple(TextParseDto item, List<TagInfo> lstTag)
        {
            var tagDatas = item.SourceProcess.Split(';');
            var oldSourceProcess = item.SourceProcess;

            foreach (var tagData in tagDatas)
            {
                item.SourceProcess = tagData;
                Text_Parse_Tag_General_Single(item, lstTag);
            }

            item.SourceProcess = oldSourceProcess;
            if (item.lstTag.Any())
            {
                if (item.Total.HasValue && item.lstTag.Sum(x => x.DataValue) != item.Total)
                {
                    item.Result = ParsemResult.ParsemResult_Warn;
                    item.ResultTip = "不等于合计";
                }
                else
                    item.Result = ParsemResult.ParsemResult_Success;
            }

            return item;
        }
    }
}
